package com.lap.permission.api;

import com.lap.framework.dto.result.Result;
import com.lap.framework.enums.ResultCode;
import com.lap.framework.exception.ExceptionHandler;
import com.lap.framework.i18n.helper.MessageHelper;
import com.lap.permission.annotation.LoginLog;
import com.lap.permission.component.JwtTokenHelper;
import com.lap.permission.domain.entity.User;
import com.lap.permission.dto.request.LoginRequest;
import com.lap.permission.dto.response.TokenDTO;
import com.lap.permission.service.UserService;
import com.lap.permission.validator.LoginValidator;
import io.jsonwebtoken.ExpiredJwtException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@Slf4j
@Tag(name = "权限访问")
@RequiredArgsConstructor
@RestController
@RequestMapping("api/auth")
public class AuthenticationController {

    private final UserService userService;

    private final JwtTokenHelper jwtTokenHelper;

    private final MessageHelper messageHelder;

    private final List<LoginValidator> validateList;

    @LoginLog
    @Operation(summary = "登录")
    @PostMapping("signIn")
    public TokenDTO login(@RequestBody @Valid LoginRequest request) {
        User query = userService.queryByUsername(request.getUsername());
        if (Objects.isNull(query))
            throw ExceptionHandler.newBiz("10103");

        for (LoginValidator validate : validateList) {
            validate.validate(request, query);
        }

        return TokenDTO.builder()
                .token(jwtTokenHelper.createJwt(query))
                .build();
    }

    @Operation(summary = "验证")
    @GetMapping("validate")
    public Result<User> validate(String token) {
        try {
            Integer userId = jwtTokenHelper.validateJwt(token);
            return Result.ok(userService.queryById(userId));
        } catch (ExpiredJwtException e) {
            return Result.failed(ResultCode.LOGIN_EXPIRE, messageHelder.getMsg("10161"));
        } catch (Exception e) {
            return Result.failed(ResultCode.LOGIN_EXPIRE, messageHelder.getMsg("10162"));
        }
    }

    @Operation(summary = "登出")
    @GetMapping("signOut")
    public Integer logout() {
        return 1;
    }

}
